import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import mglearn
import pandas as pd
import random
import numpy as np
import matplotlib.pyplot as plt

vectors_set = []
for i in range(1000):
    x0 = 1
    x1 = random.randint(1,10)
    x2 = random.randint(1,10)
    x3 = random.randint(1,10)
    x4 = random.randint(1,10)
    y = (5 + 0.3*x1 + 2*x2 + 0.5*x3 + 3*x4) + random.randint(-5,5)
    vectors_set.append([x0,x1,x2,x3,x4,y])
data = pd.DataFrame(vectors_set,columns=['x0','x1','x2','x3','x4','y'])
def h0(data,xita: tuple):
    data['y_pre'] = xita[0]*data['x0'] + xita[1]*data['x1'] + xita[2]*data['x2'] + xita[3]*data['x3'] + xita[4]*data['x4']
    j_list = []
    for i in range(len(xita)):
        j = (1/(data.shape[0])*2) * sum((data['y_pre'] - data['y']) * data['x'+str(i)])
        print('x'+str(i),j)
        j_list.append(j)
    return j_list

def j0(data,aerfa=0.0001,max_iters=10000,precision=0.00001):
    j_list = []
    xita = (0,0,0,0,0) #初始化θ参数
    for i in range(max_iters):
        print('xita：',xita)
        j = (1/(data.shape[0])*2) * sum(np.square((xita[0]*data['x0'] + xita[0]*data['x1'] + xita[0]*data['x2'] + xita[0]*data['x3'] + xita[0]*data['x4'])-data['y']))
        j_list.append(j)
        # 停止条件为代价函数不再减小或者反而开始增大
        if len(j_list) >= 2 and j_list[-2] - j_list[-1] <= precision:
            break
        j = h0(data,xita)
        xita = tuple(xita[i] - aerfa * j[i] for i in range(len(j)))
    return xita,j_list
xita,j_list=j0(data)